package com.example.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.StatFs;
import android.os.storage.StorageManager;
import androidx.annotation.RequiresApi;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

public class UsbBroadcast extends BroadcastReceiver {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onReceive(Context context, Intent intent) {

        switch (intent.getAction()) {
            case Intent.ACTION_MEDIA_MOUNTED: {
                StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
                try {
                    Class storeManagerClazz = Class.forName("android.os.storage.StorageManager");

                    Method getVolumesMethod = storeManagerClazz.getMethod("getVolumes");

                    List<?> volumeInfos  = (List<?>)getVolumesMethod.invoke(storageManager);

                    Class volumeInfoClazz = Class.forName("android.os.storage.VolumeInfo");

                    Method getTypeMethod = volumeInfoClazz.getMethod("getType");
                    Method getFsUuidMethod = volumeInfoClazz.getMethod("getFsUuid");

                    Field fsTypeField = volumeInfoClazz.getDeclaredField("fsType");
                    Field fsLabelField = volumeInfoClazz.getDeclaredField("fsLabel");
                    Field pathField = volumeInfoClazz.getDeclaredField("path");
                    Field internalPath = volumeInfoClazz.getDeclaredField("internalPath");

                    if(volumeInfos != null){
                        for(Object volumeInfo:volumeInfos){
                            String uuid = (String)getFsUuidMethod.invoke(volumeInfo);
                            if(uuid != null){
                                String fsTypeString = (String)fsTypeField.get(volumeInfo);
                                String fsLabelString = (String)fsLabelField.get(volumeInfo);
                                String pathString = (String)pathField.get(volumeInfo);
                                String internalPathString = (String)internalPath.get(volumeInfo);
                                StatFs statFs = new StatFs(internalPathString);
                                long avaibleSize = statFs.getAvailableBytes();
                                long totalSize = statFs.getTotalBytes();
                            }
                        }
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }

                break;
            }
            case Intent.ACTION_MEDIA_UNMOUNTED: {

                break;
            }
            default:
                break;
        }

    }

}
